import Vue from 'vue'
import Router from 'vue-router'
import NProgress from 'nprogress'
import { getToken } from '@/utils/cookies'
import store from '@/store/index'
import { Notification } from 'element-ui'
import { useMicro } from '@/hooks/useMicro'

NProgress.configure({ showSpinner: false })
Vue.use(Router)

const whiteList = ['/login']

const router = new Router({
	mode: 'hash',
	routes: [
		{
			path: '/login',
			component: {
				render(h) {
					return h('h3', { style: 'text-align: center;'}, '登入界面,调取父应用登入，后期接入！开发使用Token 登入')
				}
			}
		}
	]
})

const initDynamicRouter = () => {
	return new Promise((resolve, reject) => {
		store
			.dispatch('GenerateRoutes')
			.then(() => {
				router.addRoutes(store.getters.addRouters)
				resolve()
			})
			.catch(() => {
				Notification.error({
					message: '错误',
					description: '请求用户信息失败，请重试'
				})
				// 失败时，获取用户信息失败时，调用登出，来清空历史保留信息
				// store.dispatch('Logout').then(() => {
				// 	next({ path: '/login', query: { redirect: to.fullPath } })
				// })
				reject()
			})
	})
}

router.beforeEach(async (to, from, next) => {
	const micro = useMicro()

	NProgress.start()
	/* has token */
	if (getToken()) {
		if (to.path.toLocaleLowerCase() === '/login') {
			if (getToken()) return next(from.fullPath)
			return next()
		}

		if (!micro.isMicro) {
			if (!store.getters.addRouters.length) {
				await initDynamicRouter()
				return next({ ...to, replace: true })
			}
			next()
		} else {
			if (!store.getters.addRouters.length) {
				await initDynamicRouter()
				return next({ ...to, replace: true })
			}
			next()
		}
	} else {
		if (whiteList.includes(to.path)) {
			next()
		} else {
			next({ path: '/login', replace: true })
			NProgress.done()
		}
	}
})

router.afterEach(() => {
	NProgress.done() // finish progress bar
})

export default router
